package com.atguigu.gmall.pms.service.impl;

import com.atguigu.gmall.pms.entity.SkuAttrValueEntity;
import com.atguigu.gmall.pms.entity.SkuImagesEntity;
import com.atguigu.gmall.pms.entity.SpuEntity;
import com.atguigu.gmall.pms.feign.GmallSmsClient;
import com.atguigu.gmall.pms.mapper.SkuMapper;
import com.atguigu.gmall.pms.service.*;
import com.atguigu.gmall.pms.vo.SkuVo;
import com.atguigu.gmall.pms.vo.SpuVo;
import com.atguigu.gmall.sms.vo.SkuSaveVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.pms.mapper.SpuMapper;

import javax.annotation.Resource;


@Service("spuService")
public class SpuServiceImpl extends ServiceImpl<SpuMapper, SpuEntity> implements SpuService {

    @Resource
    private SpuDescService spuDescService;
    @Resource
    private SkuMapper skuMapper;
    @Resource
    private SpuAttrValueService spuAttrValueService;
    @Resource
    private SkuImagesService skuImagesService;
    @Resource
    private SkuAttrValueService skuAttrValueService;
    @Resource
    private GmallSmsClient smsClient;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<SpuEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<SpuEntity>()
        );

        return new PageResultVo(page);
    }

    @Override
    public PageResultVo pageByCid(Long cid, PageParamVo paramVo) {
        LambdaQueryWrapper<SpuEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpuEntity::getCategoryId,cid);
        String key = paramVo.getKey();
        if (StringUtils.isNotBlank(key)){
            queryWrapper.and(w -> w.like(SpuEntity::getId,key)
                    .or().like(SpuEntity::getId,key));
        }
        IPage<SpuEntity> page = this.page(paramVo.getPage(), queryWrapper);
        return new PageResultVo(page);

    }

    //保存spu、sku及sms的优惠策略
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void saveBySpuVo(SpuVo spu) {
        //保存spu相关的信息
        //保存pms_spu表信息
        Long spuId = getSpuId(spu);
        //保存pms_desc信息
        spuDescService.savePmsDesc(spu, spuId);

        //保存pms_spu_attr_value信息
        spuAttrValueService.savePmsSpuAttrValue(spu, spuId);

        //保存sku相关的信息
        //保存pms_sku
        this.saveSkuOrSmsBounds(spu, spuId);
        rabbitTemplate.convertAndSend("PMS.SPU.EXCHANGE","item.insert",spuId);

    }


    private void saveSkuOrSmsBounds(SpuVo spu, Long spuId) {
        List<SkuVo> sku = spu.getSkus();//获取skus属性对象
        if (CollectionUtils.isEmpty(sku)){
            return;
        }
        sku.forEach(skuVo -> {//迭代
            //保存pms_sku_images
            skuVo.setSpuId(spuId);
            skuVo.setBrandId(spu.getBrandId());
            skuVo.setCategoryId(spu.getCategoryId());
            //获取图片列表
            List<String> images = skuVo.getImages();
            if (CollectionUtils.isNotEmpty(images)){
                skuVo.setDefaultImage(
                        //设置默认图片，如果默认图片存在就用默认图片，如果默认图片不存在就用图片第一张
                        StringUtils.isBlank(skuVo.getDefaultImage())? images.get(0) : skuVo.getDefaultImage()
                );
            }
            skuMapper.insert(skuVo);//保存sku表信息
            Long skuId = skuVo.getId();

            //保存pms_sku_images
            if (CollectionUtils.isNotEmpty(images)){//如果sku的图片不为空
                skuImagesService.saveBatch(images.stream().map(skuImages->{
                            SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                            skuImagesEntity.setSkuId(skuId);
                            skuImagesEntity.setUrl(skuImages);
                            skuImagesEntity.setDefaultStatus(
                                    //如果当前图片和默认图片一致则默认状态设置为1
                                    StringUtils.equals(skuImages,skuVo.getDefaultImage())?1:0
                            );
                            return skuImagesEntity;
                }).collect(Collectors.toList())
                );
            }

            //保存pms_sku_attr_value
            List<SkuAttrValueEntity> saleAttrs = skuVo.getSaleAttrs();
            if (CollectionUtils.isNotEmpty(saleAttrs)){
                saleAttrs.forEach(attrs->{
                    attrs.setSkuId(skuId);
                });
                skuAttrValueService.saveBatch(saleAttrs);
            }
            //保存营销信息
            SkuSaveVo skuSaveVo = new SkuSaveVo();
            BeanUtils.copyProperties(skuVo,skuSaveVo);
            skuSaveVo.setSkuId(skuId);
            smsClient.saveSales(skuSaveVo);//远程调用
        });
    }
    private Long getSpuId(SpuVo spu) {
        spu.setCreateTime(new Date());//设置创建时间
        spu.setUpdateTime(spu.getCreateTime());
        this.save(spu);//调用保存方法，会根据字段名进行存储
        Long spuId = spu.getId();//获取id并返回
        return spuId;
    }

}